/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using NS_Controls;

public partial class HumanResource : SessionPageBase
{
	private static string sql = "SelectHumanResources", sessionKey = "ds_" + sql;
	private static string chartTitle = "Indicatori Resurse Umane";

	protected void Page_Load(object sender, EventArgs e)
	{
		try
		{
			SetEventHandlers();
			if (!IsPostBack)
			{
                txtStartDate.Text = System.DateTime.Now.ToShortDateString();
                txtEndDate.Text = System.DateTime.Now.ToShortDateString();

				ClearSession(sessionKey);
				Load_Data(false);
				ddlSelectAllDiagrame.SelectedValue = "Pie";
				ddlSelectAllDiagrame_SelectedIndexChanged(null, null);
			}
			else
				RebuildCharts();

		}
		catch (Exception ex)
		{
			output.Text = "<!--" + ex.ToString() + "-->";
			this.Master.SetMessage(ex.Message, true);
		}
	}

	private void SetEventHandlers()
	{
		foreach (ExtendedGridView gr in new ExtendedGridView[] { grPersonalMedical, grAsistMedical, grProp, grPropMed, grStudSup, grNrMediuCons, grNrConsMedic })
		{
			gr.DataSourceChanged += new EventHandler(ExtGridView_DataSourceChanged);
			gr.PageIndexChanged += new EventHandler(ExtGridView_DataSourceChanged);
		}
	}

	private void ExtGridView_DataSourceChanged(object sender, EventArgs e)
	{
		ExtendedGridView source = sender as ExtendedGridView;
		System.Web.UI.DataVisualization.Charting.Chart c = source.Parent.FindControl(source.ID.Replace("gr", "chart")) as System.Web.UI.DataVisualization.Charting.Chart;
		DropDownList ddl = null;

		foreach (Control child in source.Parent.Controls) if (child is DropDownList) ddl = child as DropDownList;
		if (c != null)
			BuildChart(c, source, ddl.SelectedValue);
	}

	private void Load_Data(bool bForce)
	{
		try
		{
			string[] chartTypes = GetChartTypes();
			ddlSelectAllDiagrame.DataSource = chartTypes;
			ddlSelectAllDiagrame.DataBind();

			DataTable dtActiveTabs = Hipocrate.DB.DBConnection.GetData("SELECT TabCode, Active FROM Doc_Type_Tabs WHERE page = 'HR' OR page IS NULL").Tables[0];
			System.Collections.Generic.Dictionary<string, bool> active = new System.Collections.Generic.Dictionary<string, bool>();
			foreach (DataRow tab in dtActiveTabs.Rows)
				active[tab["TabCode"].ToString()] = System.Convert.ToBoolean(tab["Active"]);

			int nrCrt = 0;

			if (tab1.Visible = active["PersonalMedical"]) //assignment is on purpose
			{
				Load_Grid(grPersonalMedical, 0, bForce);
				ddlSelectDiagram1.DataSource = chartTypes;
				ddlSelectDiagram1.DataBind();
				//SetTabHeaderPrefix(tab1, ++nrCrt);
			}

			if (tab2.Visible = active["AsistMedical"]) //assignment is on purpose
			{
				Load_Grid(grAsistMedical, 1, bForce);
				ddlSelectDiagram2.DataSource = chartTypes;
				ddlSelectDiagram2.DataBind();
				//SetTabHeaderPrefix(tab2, ++nrCrt);
			}

			if (tab3.Visible = active["Prop"]) //assignment is on purpose
			{
				Load_Grid(grProp, 2, bForce);
				ddlSelectDiagram3.DataSource = chartTypes;
				ddlSelectDiagram3.DataBind();
				//SetTabHeaderPrefix(tab3, ++nrCrt);
			}

			if (tab4.Visible = active["PropMed"]) //assignment is on purpose
			{
				Load_Grid(grPropMed, 3, bForce);
				ddlSelectDiagram4.DataSource = chartTypes;
				ddlSelectDiagram4.DataBind();
				//SetTabHeaderPrefix(tab4, ++nrCrt);
			}

			if (tab5.Visible = active["StudSup"]) //assignment is on purpose
			{
				Load_Grid(grStudSup, 4, bForce);
				ddlSelectDiagram5.DataSource = chartTypes;
				ddlSelectDiagram5.DataBind();
				//SetTabHeaderPrefix(tab5, ++nrCrt);
			}

			if (tab6.Visible = active["NrMediuCons"]) //assignment is on purpose
			{
				Load_Grid(grNrMediuCons, 5, bForce);
				ddlSelectDiagram6.DataSource = chartTypes;
				ddlSelectDiagram6.DataBind();
				//SetTabHeaderPrefix(tab6, ++nrCrt);
			}

			if (tab7.Visible = active["NrConsMedic"]) //assignment is on purpose
			{
				Load_Grid(grNrConsMedic, 6, bForce);
				ddlSelectDiagram7.DataSource = chartTypes;
				ddlSelectDiagram7.DataBind();
				//SetTabHeaderPrefix(tab7, ++nrCrt);
			}
		}
		catch (Exception ex)
		{
			this.Master.SetMessage(ex.Message, true);
		}
	}

	protected void ddlSelectAllDiagrame_SelectedIndexChanged(object sender, EventArgs e)
	{
		string selectedValue = ddlSelectAllDiagrame.SelectedValue;
		foreach (DropDownList ddl in new DropDownList[] { ddlSelectDiagram1, ddlSelectDiagram2, ddlSelectDiagram3, ddlSelectDiagram4, ddlSelectDiagram5, ddlSelectDiagram6, ddlSelectDiagram7 })
		{
			ddl.SelectedValue = selectedValue;
			ddlSelectSpecificDiagram(ddl, null);
		}
	}

	protected void ddlSelectSpecificDiagram(object sender, EventArgs e)
	{
		DropDownList ddl = sender as DropDownList;
		if (ddl == null) return;

		SeriesChartType selectedType;
		try
		{
			selectedType = GetChartType(ddl.SelectedValue);
		}
		catch (ArgumentException) //Must specify valid information for parsing in the string.
		{
			return;
		}
		Chart chart = null;

		foreach (Control c in ddl.Parent.Controls)
			if (c is System.Web.UI.DataVisualization.Charting.Chart)
			{
				chart = c as System.Web.UI.DataVisualization.Charting.Chart;
				foreach (System.Web.UI.DataVisualization.Charting.Series s in chart.Series)
					s.ChartType = selectedType;
				break; //only set the type for the first chart, if there are more
			}
	}

	private string[] GetChartTypes()
	{
		object[] fields = typeof(System.Web.UI.DataVisualization.Charting.SeriesChartType).GetFields();
		List<string> result = new List<string>(fields.Length);
		foreach (System.Reflection.FieldInfo fi in fields)
			if (fi.IsStatic)
				result.Add(fi.Name);
		result.Sort();
		//remove the useless ones:
		result.Remove("PointAndFigure");
		result.Remove("StackedArea100");
		result.Remove("StackedBar100");
		result.Remove("StackedColumn100");
		result.Remove("ThreeLineBreak");

		//second approach: white-list!
		result.Clear();
		result.Add("Area");
		result.Add("Bar");
		result.Add("Column");
		result.Add("Doughnut");
		result.Add("Pie");
		result.Add("Range");
		result.Add("Spline");
		result.Add("SplineArea");
		result.Add("SplineRange");
		result.Add("StackedArea");
		return result.ToArray();
	}

	private void Load_Grid(ExtendedGridView target, int tableIndex, bool bForceReload)
	{
		DataSet fullBundle = GetSession(sessionKey) as DataSet;
		#region rebuild DataSet
		if (fullBundle == null || bForceReload)
		{
			fullBundle = BuildSessionDataSet(sessionKey, sql, new string[] { "StartDate", "EndDate" }, new object[] { CommonSession.StareDiagramaIndicatori.GetDate(txtStartDate), CommonSession.StareDiagramaIndicatori.GetDate(txtEndDate) });
			//add column for percentage:
			foreach (DataTable dt in fullBundle.Tables)
			{
				dt.Columns.Add("Percentage");
				decimal sum = 0;
				foreach (DataRow dr in dt.Rows)
					sum += System.Convert.ToDecimal(dr["nrExtern"]);

				foreach (DataRow dr in dt.Rows)
				{
					decimal currentValue = System.Convert.ToDecimal(dr["nrExtern"]);
					dr["Percentage"] = (currentValue == 0 ? 0 : System.Convert.ToInt32(100 * currentValue / sum));
				}
			}

			SetSession(sessionKey, fullBundle);
		}
		#endregion
		if (fullBundle != null && (bForceReload || !IsPostBack))
		{
			DataTable data = fullBundle.Tables[tableIndex];

			target.SessionKey = GetSessionKey(sessionKey);
			target.SessionKeyIndex = tableIndex;
			target.SessionKeyFilter = "";
			target.DataSource = data.DefaultView;
			target.DataBind();
		}
	}

	private void RebuildCharts()
	{
		DataSet fullBundle = GetSession(sessionKey) as DataSet;

		if (fullBundle == null)
			return;

		BuildChart(chartPersonalMedical, grPersonalMedical, ddlSelectDiagram1.SelectedValue);
		BuildChart(chartAsistMedical, grAsistMedical, ddlSelectDiagram2.SelectedValue);
		BuildChart(chartProp, grProp, ddlSelectDiagram3.SelectedValue);
		BuildChart(chartPropMed, grPropMed, ddlSelectDiagram4.SelectedValue);
		BuildChart(chartStudSup, grStudSup, ddlSelectDiagram5.SelectedValue);
		BuildChart(chartNrMediuCons, grNrMediuCons, ddlSelectDiagram6.SelectedValue);
		BuildChart(chartNrConsMedic, grNrConsMedic, ddlSelectDiagram7.SelectedValue);
	}

	private void BuildChart(System.Web.UI.DataVisualization.Charting.Chart target, ExtendedGridView data, string chartType)
	{
		if (data.DataSource == null)
		{
			target.Titles[0].Text = "No data"; //a bit useless, since it's within a tab that will not be shown...
			return;
		}
		if (!target.Titles[0].Text.Equals(chartTitle))
		{
			Tools.ScrieInLog(Server, "Chart title for '" + target.ID + "' was '" + target.Titles[0].Text + "' instead of '" + chartTitle + "'.");
			target.Titles[0].Text = chartTitle;
		}
		target.Series.Clear();
		target.Series.Add("Procentaj");
		if (!string.IsNullOrEmpty(chartType))
			target.Series[0].ChartType = GetChartType(chartType);

		decimal sum = 0;
		foreach (DataRowView rv in data.DataSource)
			sum += System.Convert.ToDecimal(rv["nrExtern"]);

		int pgOffset = data.PageSize * data.PageIndex;
		while ((data.DataSource.Count <= pgOffset) && (pgOffset > 0))
			pgOffset -= data.PageSize;

		decimal runningTotal = 0;
		int nRowCount = data.PageSize;
		if (nRowCount < 0)
		{
			nRowCount = data.DataSource.Count;
			pgOffset = 0;
		}
		for (int i = 0; i < nRowCount; ++i)
			if ((i + pgOffset) < data.DataSource.Count)
			{
				DataRowView dr = data.DataSource[i + pgOffset];
				runningTotal += System.Convert.ToDecimal(dr["nrExtern"]);
				target.Series[0].Points.AddXY(dr["Percentage"].ToString() + "%", dr["nrExtern"]);
				target.Series[0].Points[target.Series[0].Points.Count - 1].LegendText = dr["ID"].ToString();
			}
		//target.Series[0].Points.AddXY(System.Convert.ToInt32(100 * (sum - runningTotal) / sum).ToString() + "%", sum - runningTotal);
		//target.Series[0].Points[target.Series[0].Points.Count - 1].LegendText = "other";
	}

	private System.Web.UI.DataVisualization.Charting.SeriesChartType GetChartType(string chartType)
	{
		return (System.Web.UI.DataVisualization.Charting.SeriesChartType)Enum.Parse(typeof(System.Web.UI.DataVisualization.Charting.SeriesChartType), chartType);
	}

	protected void btn_Load(object sender, EventArgs e)
	{
		try
		{
			Load_Data(true);
		}
		catch (Exception ex)
		{
			output.Text = "<!--" + ex.ToString() + "-->";
			this.Master.SetMessage(ex.Message, true);
		}
	}

	#region Print Preview
	protected void btnPreview1_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grPersonalMedical, tab1, 0, ddlSelectDiagram1), true);
	}
	protected void btnPreview2_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grAsistMedical, tab2, 1, ddlSelectDiagram2), true);
	}
	protected void btnPreview3_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grProp, tab3, 2, ddlSelectDiagram3), true);
	}
	protected void btnPreview4_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grPropMed, tab4, 3, ddlSelectDiagram4), true);
	}
	protected void btnPreview5_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grStudSup, tab5, 4, ddlSelectDiagram5), true);
	}
	protected void btnPreview6_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grNrMediuCons, tab6, 5, ddlSelectDiagram6), true);
	}
	protected void btnPreview7_Click(object sender, EventArgs e)
	{
		Response.Redirect("Preview.aspx?info=" + GetGuid(grNrConsMedic, tab7, 6, ddlSelectDiagram7), true);
	}

	private string GetGuid(ExtendedGridView gv, AjaxControlToolkit.TabPanel t, int i, DropDownList ddl)
	{
		return CommonSession.SetStareDiagramaIndicatori(this, chartTitle, t.HeaderTemplate, sql, txtStartDate, txtEndDate,
			i, gv.PageSize, gv.PageIndex, gv.GetRowFilter(), gv.GridViewSortExpression, gv.GridViewSortDirection, gv.Columns, ddl.SelectedValue);
	}
	#endregion
}
